from typing import List, Optional
from repositories.item_repository import ItemRepository
from models.item import Item
from schemas.item import ItemCreate, ItemUpdate, ItemResponse, ItemListResponse
from fastapi import HTTPException

class ItemService:
    """商品业务逻辑层"""
    
    def __init__(self, repository: ItemRepository):
        self.repository = repository
    
    def get_items(self, skip: int = 0, limit: int = 100) -> ItemListResponse:
        """获取商品列表"""
        if skip < 0:
            raise HTTPException(status_code=400, detail="skip参数不能为负数")
        if limit <= 0 or limit > 1000:
            raise HTTPException(status_code=400, detail="limit参数必须在1-1000之间")
        
        items = self.repository.get_all(skip, limit)
        total = self.repository.count()
        
        item_responses = [ItemResponse(**item.to_dict()) for item in items]
        
        return ItemListResponse(
            items=item_responses,
            total=total,
            skip=skip,
            limit=limit
        )
    
    def get_item_by_id(self, item_id: int) -> ItemResponse:
        """根据ID获取商品"""
        if item_id <= 0:
            raise HTTPException(status_code=400, detail="商品ID必须为正整数")
        
        item = self.repository.get_by_id(item_id)
        if not item:
            raise HTTPException(status_code=404, detail=f"商品ID {item_id} 未找到")
        
        return ItemResponse(**item.to_dict())
    
    def create_item(self, item_create: ItemCreate) -> ItemResponse:
        """创建新商品"""
        # 业务逻辑验证
        if item_create.price <= 0:
            raise HTTPException(status_code=400, detail="商品价格必须大于0")
        
        # 检查是否存在同名商品（可选的业务规则）
        existing_items = self.repository.get_all()
        if any(item.name.lower() == item_create.name.lower() for item in existing_items):
            raise HTTPException(status_code=400, detail=f"商品名称 '{item_create.name}' 已存在")
        
        item_data = item_create.dict()
        created_item = self.repository.create(item_data)
        
        return ItemResponse(**created_item.to_dict())
    
    def update_item(self, item_id: int, item_update: ItemUpdate) -> ItemResponse:
        """更新商品"""
        if item_id <= 0:
            raise HTTPException(status_code=400, detail="商品ID必须为正整数")
        
        if not self.repository.exists(item_id):
            raise HTTPException(status_code=404, detail=f"商品ID {item_id} 未找到")
        
        update_data = item_update.dict(exclude_unset=True)
        if not update_data:
            raise HTTPException(status_code=400, detail="至少需要提供一个要更新的字段")
        
        # 业务逻辑验证
        if "price" in update_data and update_data["price"] <= 0:
            raise HTTPException(status_code=400, detail="商品价格必须大于0")
        
        updated_item = self.repository.update(item_id, update_data)
        return ItemResponse(**updated_item.to_dict())
    
    def delete_item(self, item_id: int) -> dict:
        """删除商品"""
        if item_id <= 0:
            raise HTTPException(status_code=400, detail="商品ID必须为正整数")
        
        deleted_item = self.repository.delete(item_id)
        if not deleted_item:
            raise HTTPException(status_code=404, detail=f"商品ID {item_id} 未找到")
        
        return {"message": f"商品 '{deleted_item.name}' (ID: {item_id}) 已成功删除"}
    
    def get_categories(self) -> dict:
        """获取所有商品分类"""
        categories = self.repository.get_categories()
        return {
            "categories": sorted(categories),
            "count": len(categories)
        }
    
    def get_items_by_category(self, category: str) -> List[ItemResponse]:
        """根据分类获取商品"""
        if not category.strip():
            raise HTTPException(status_code=400, detail="分类名称不能为空")
        
        items = self.repository.get_by_category(category)
        if not items:
            available_categories = self.repository.get_categories()
            raise HTTPException(
                status_code=404, 
                detail=f"分类 '{category}' 下没有找到商品。可用分类: {', '.join(available_categories)}"
            )
        
        return [ItemResponse(**item.to_dict()) for item in items]
    
    def demo_crud_operations(self) -> dict:
        """Demo: 演示Service层的CRUD调用链"""
        
        # 1. 创建Demo商品 (Service层业务逻辑)
        demo_create = ItemCreate(
            name="Service层Demo商品",
            description="演示Service层调用Repository层",
            price=88.88,
            category="Service Demo"
        )
        
        # 调用Repository层创建
        created_item = self.create_item(demo_create)
        
        # 2. 查询Demo商品 (Service层调用Repository层)
        read_item = self.get_item_by_id(created_item.id)
        
        # 3. 更新Demo商品
        update_data = ItemUpdate(price=168.88)
        updated_item = self.update_item(created_item.id, update_data)
        
        return {
            "service_layer_demo": "Service层调用Repository层Demo",
            "数据转换": {
                "输入": "Schemas (ItemCreate, ItemUpdate)",
                "处理": "Service层业务逻辑验证",
                "调用": "Repository层 (只传递dict给Repository)",
                "输出": "Schemas (ItemResponse)"
            },
            "operations": {
                "created": created_item.dict(),
                "read": read_item.dict(), 
                "updated": updated_item.dict()
            }
        } 